package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

func AllowCors() gin.HandlerFunc {
	return func(c *gin.Context) {
		fmt.Println(c.Request.URL.Path)
		method := c.Request.Method
		origin := c.Request.Header.Get("origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Method", "GET,POST,OPTIONS,DELETE,PUT,UPDATE")
			c.Header("Access-Control-Allow-Origin", origin)
			c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token,Authorization,Token,X-Token,X-User-Id")
			c.Header("Access-Control-Expose-Headers", "Content-Length,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Content-Type,New-Token,New-Expires-At")
			c.Header("Access-Control-Credentials", "true")
		}
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}
